package com.example.paper.interceptor;

import com.example.paper.http.logUtils.LogUtils;
import com.example.paper.http.logUtils.MD5Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

public class SignInterceptor implements Interceptor {

    //为了防止篡改

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request oldRequest = chain.request();

        Request.Builder builder = new Request.Builder();
        builder.url(oldRequest.url());
        builder.headers(oldRequest.headers());

        RequestBody oldBody = oldRequest.body();

        Buffer buffer = new Buffer();
        oldBody.writeTo(buffer);
        String oldJson = "";
        byte[] bytes = new byte[1024];
        while (buffer.read(bytes) != -1) {
            oldJson += new String(bytes);
        }
        buffer.close();
        oldJson.trim();
        LogUtils.e("oldJson"+oldJson);

        String valuse = "";
        String json = "";
        try {
            JSONObject jsonObject = new JSONObject(oldJson);
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()){
                valuse += jsonObject.getString(keys.next());
            }
            String sign = MD5Utils.createString(valuse);
            jsonObject.put("sign",sign);
            json = jsonObject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LogUtils.e("json"+json);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        builder.post(body);

        return chain.proceed(builder.build());
    }
}
